package com.zebra.base.vo;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.zebra.base.exception.ZebraException;
import com.zebra.base.msgcode.MsgCode;
import com.zebra.base.msgcode.SuccessCode;
import com.zebra.base.msgcode.SysErrorCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;

/**
 * @ClassName Res
 * @Description TODO 所有后端Rest请求需统一返回此对象
 * @Author 消魂钉
 * @Date 6/1 0001 10:27
 */
@ApiModel(description = "所有Rest请求返回的对象")
@Data
public class Res<T> {

    private final static SuccessCode SUCCESS_CODE = SuccessCode.SUCCESS;

    @ApiModelProperty(value = "处理代码", required = true)
    private String code;
    @ApiModelProperty(value = "处理结果描述", required = true)
    private String msg;
    @ApiModelProperty(value = "返回时间")
    @Builder.Default
    private String datetime = "";
    @ApiModelProperty(value = "处理结果信息返回")
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T result;

    public Res(MsgCode errorCode) {
        this.code = errorCode.getCode();
        this.msg = errorCode.getMsg();
        this.datetime = DateUtil.now();
    }

    /**
     * @param msgCode 传递编码
     * @param result
     */
    public Res(MsgCode msgCode, T result) {
        this(msgCode);
        this.result = result;
    }

    /**
     * 成功有返回值
     * @param
     * @return result
     */
    public static Res success(Object result) {
        return new Res<>(SUCCESS_CODE, result);
    }

    /**
     * 成功没有返回值
     * @return 返回的参数
     */
    public static Res success() {
        return success(null);
    }


    /**
     * 系统异常类没有返回数据
     *
     * @return Res 返回的参数
     */
    public static Res fail() {
        return new Res(SysErrorCode.ERROR);
    }

    /**
     * 系统异常类并返回结果数据
     *
     * @param result
     * @return Res 返回的参数
     */
    public static Res fail(ZebraException zebraException, Object result) {
        return new Res<>(zebraException.getErrorCode(), result);
    }


}
